package cn.wegoteam.shop.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.wegoteam.shop.inter.AddressServiceInter;
import cn.wegoteam.shop.inter.BaseDaoInter;
import cn.wegoteam.shop.po.Address;
import cn.wegoteam.shop.po.User;
import cn.wegoteam.shop.util.DataUtils;
import cn.wegoteam.shop.util.MyString;
@Service("addressService")
public class AddressService extends BaseService<Address> implements
		AddressServiceInter {
	    @Resource(name="addressService")
	    private AddressServiceInter addressService;
        @Resource(name="addressDao")
        public void setBaseDao(BaseDaoInter<Address> baseDao) {
        	// TODO Auto-generated method stub
        	super.setBaseDao(baseDao);
        }
		public int updateAddrBySql(Address addr) {
			if(addr.getId()==null){
				return 0;
			}
			Map<String,Object> map=new HashMap<String, Object>();
			StringBuilder sql=new StringBuilder("update address set id=id ");
			if(!MyString.isEmpty(addr.getSubarea())){
				sql.append(",subarea=:subarea");
				map.put("subarea", addr.getSubarea());
			}
			if(!MyString.isEmpty(addr.getDetailAddress())){
				sql.append(",detailAddress=:detailAddress");
				map.put("detailAddress", addr.getDetailAddress());
			}
			if(!MyString.isEmpty(addr.getPostcode())){
				sql.append(",postcode=:postcode");
				map.put("postcode", addr.getPostcode());
			}
			if(!MyString.isEmpty(addr.getAccepter())){
				sql.append(",accepter=:accepter");
				map.put("accepter", addr.getAccepter());
			}
			if(!MyString.isEmpty(addr.getPhone())){
				sql.append(",phone=:phone");
				map.put("phone", addr.getPhone());
			}
			if(!MyString.isEmpty(addr.getTelephone())){
				sql.append(",telephone=:telephone");
				map.put("telephone", addr.getTelephone());
			}
			if(!MyString.isEmpty(addr.getDef())){
				sql.append(",def=:def");
				map.put("def", addr.getDef());
			}
			sql.append(" where id="+addr.getId());
			System.out.println(sql.toString());
			return super.executeBySql(sql.toString(), map);
		}
	    //切换收获地址的状态
		@Transactional(propagation = Propagation.SUPPORTS)
		public void toggleStatus(Address model, User user) {
			  System.out.println(user.getId());
			  this.toggleDefStatus(user);
              executeBySql("update address set def=:def where id=:id", DataUtils.getMap("def","2","id",model.getId()));
		}
		@Transactional(propagation = Propagation.SUPPORTS)
		public void toggleDefStatus(User user) {
			// TODO Auto-generated method stub
			 executeByHql("update Address set def=:def where user.id=:id ",DataUtils.getMap("def","1","id",user.getId()));
		}
}
